 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=187 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:47 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Model Objects
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='DAO,data&#045;centric,datacentric,immutable,JavaBean,Message,MO,MyUser,design pattern,value object,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Model Objects</div>

<div class='main-body'>
 
<br>The term Model Object is an informal term, with no widely accepted
definition. Here, Model Objects (MOs) refer to data-centric classes which
encapsulate closely related items. 

<p>Model Objects :
<ul>
<li>
are very common, and are used in almost all applications</li>

<li>
are often central to an application, since they usually model problem domain
objects</li>

<li>
often map roughly to the records of a corresponding database table</li>

<li>
are often used as return values for <a href="TopicAction564b-2.html">Data Access Object</a>
methods</li>

<li>
are easily tested using <a href="TopicActiond5a5-2.html">JUnit</a> (or a similar tool)</li>

<li>
can be used to implement the Model in a <a href="TopicActiona7f6-2.html">Model-View-Controller</a>
pattern</li>
</ul>
<em>Should Model Objects follow the JavaBeans conventions?</em>

<p>Not necessarily. In fact, some argue that the JavaBeans style is <a href="TopicActionfbbc-2.html">to
be avoided</a> as a general model for Model Objects.

<p><em>Should Model Objects be immutable?</em>

<p>Given the deep simplicity of <a href="TopicActiond838-2.html">immutable objects</a>,
some prefer to design their Model Objects as immutable. However, when the
underlying data changes, a new object must be created, instead of simply
calling a <tt>setXXX</tt> method on an existing object. Some argue that
this penalty is too high, while others argue that it is a micro-optimization
- especially in cases where the data is "read-mostly", and the state of
corresponding Model Objects changes only rarely.

<P>Implementing Model Objects as immutable seems particularly natural in web applications. 
There, Model Objects are most commonly placed in <em>request</em> scope, not session scope. 
In this case, there is no long-lived object for the user to <em>directly</em> alter, so 
the Model Object can be immutable.

<p><b>Example</b>

<p><tt>Comment</tt> represents a comment posted to a message board.
Its implementation follows the <a href="TopicActiond838-2.html">Immutable Object</a>
pattern.
<tt>Comment</tt> provides the usual <tt>getXXX</tt> methods. Note
that, in this case, a
<a href="TopicAction79f1-2.html">defensive copy</a> is used
for the <tt>Date</tt> field. It also implements the <tt><a href="TopicActionc3b3-2.html">toString</a></tt>,
<tt><a href="TopicAction1deb-2.html">equals</a></tt>,
and <tt><a href="TopicAction78db-2.html">hashCode</a></tt> methods.

<p>The constructor is responsible for establishing the <a href="TopicAction0d31-2.html">class
invariant</a>, and performs <a href='TopicAction0ec8-2.html'>Model Object validation</a>.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.fish.main.discussion; 

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelUtil;
<span class='keyword'>import</span> hirondelle.web4j.model.Check;
<span class='keyword'>import</span> hirondelle.web4j.security.SafeText;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.util.Consts.FAILS;

<span class='comment'>/** 
 Comment posted by a possibly-anonymous user.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Comment { 

  <span class='comment'>/**
   Constructor. 
     
   @param aUserName identifies the logged in user posting the comment. 
   @param aBody the comment, must have content.
   @param aDate date and time when the message was posted.
  */</span>
  <span class='keyword'>public</span> Comment (
    SafeText aUserName, SafeText aBody, Date aDate
  ) <span class='keyword'>throws</span> ModelCtorException {
    fUserName = aUserName;
    fBody = aBody;
    fDate = aDate.getTime();
    validateState();
  }

  <span class='comment'>/** Return the logged in user name passed to the constructor. */</span>
  <span class='keyword'>public</span> SafeText getUserName() {
    <span class='keyword'>return</span> fUserName;
  }

  <span class='comment'>/** Return the body of the message passed to the constructor.  */</span>
  <span class='keyword'>public</span> SafeText getBody() {
    <span class='keyword'>return</span> fBody;
  }

  <span class='comment'>/**
   Return a &lt;a href="http://www.javapractices.com/Topic15.cjp"&gt;defensive copy&lt;/a&gt; 
   of the date passed to the constructor.
   
   &lt;P&gt;The caller may change the state of the returned value, without affecting 
   the internals of this &lt;tt&gt;Comment&lt;/tt&gt;. Such copying is needed since 
   a {@link Date} is a mutable object.
  */</span>
  <span class='keyword'>public</span> Date getDate() {
    <span class='comment'>// the returned object is independent of fDate
</span>    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDate);
  }

  <span class='comment'>/** Intended for debugging only. */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() {
    <span class='keyword'>return</span> ModelUtil.toStringFor(<span class='keyword'>this</span>);
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>boolean</span> equals( Object aThat ) {
    Boolean result = ModelUtil.quickEquals(<span class='keyword'>this</span>, aThat);
    <span class='keyword'>if</span> ( result == <span class='keyword'>null</span> ){
      Comment that = (Comment) aThat;
      result = ModelUtil.equalsFor(
        <span class='keyword'>this</span>.getSignificantFields(), that.getSignificantFields()
      );
    }
    <span class='keyword'>return</span> result;    
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>int</span> hashCode() {
    <span class='keyword'>if</span> ( fHashCode == <span class='literal'>0</span> ) {
      fHashCode = ModelUtil.hashCodeFor(getSignificantFields());
    }
    <span class='keyword'>return</span> fHashCode;
  }

  <span class='comment'>// PRIVATE // 
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fUserName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fBody;
  <span class='comment'>/** Long is used here instead of Date in order to ensure immutability.*/</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>long</span> fDate;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fHashCode;
  
  <span class='keyword'>private</span> Object[] getSignificantFields(){
    <span class='keyword'>return</span> <span class='keyword'>new</span> Object[] {fUserName, fBody, <span class='keyword'>new</span> Date(fDate)};
  }
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> validateState() <span class='keyword'>throws</span> ModelCtorException {
    ModelCtorException ex = <span class='keyword'>new</span> ModelCtorException();
    <span class='keyword'>if</span>( FAILS ==  Check.required(fUserName) ) {
      ex.add(<span class='literal'>"User name must have content."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.required(fBody) ) {
      ex.add(<span class='literal'>"Comment body must have content."</span>);
    }
    <span class='keyword'>if</span> ( ! ex.isEmpty() ) <span class='keyword'>throw</span> ex;
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction0d31-2.html?Id=6'>Validate state with class invariants</a> <br>
 
  
  <a href='TopicAction79f1-2.html?Id=15'>Defensive copying</a> <br>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicActiond5a5-2.html?Id=33'>Use a testing framework (JUnit)</a> <br>
 
  
  <a href='TopicAction564b-2.html?Id=66'>Data access objects</a> <br>
 
  
  <a href='TopicActionfbbc-2.html?Id=84'>Avoid JavaBeans style of construction</a> <br>
 
  
  <a href='TopicActiona7f6-2.html?Id=108'>Use Model-View-Controller framework</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
  
  <a href='TopicAction0ec8-2.html?Id=209'>Validation belongs in a Model Object</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='187'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=187 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:48 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
